package com.lyy.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.lyy.entity.Banner;
import com.lyy.mapper.BannerMapper;
import com.lyy.service.BannerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.CacheNamespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liangyaoyun
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "lesson:cache:banner")
public class BannerServiceImpl implements BannerService {
    @Autowired
    private BannerMapper bannerMapper;

    @Cacheable(key = "'top_' + #size", condition = "#size != null and #size <= 5")
    @Override
    public List<Banner> top(Integer size) {

        // DB: 查询 [轮播图]
        List<Banner> result = bannerMapper.select(new Banner());
        if (ObjectUtil.isEmpty(result)) {
            log.error("Banner查询失败: 暂无轮播图记录，请联系运维人员");
            throw new RuntimeException("暂无轮播图记录");
        }

        // 截取前size条 [轮播图] 记录并返回
        // 这里不能直接返回subList()结果，因为无法序列化，会导致SpringCache报错
        size = Math.min(size, 5);

        return new ArrayList<>(result.subList(0, size));
    }
}
